
#include "custom.h"

#include "../filesystem_monitor.h"
#include "../utils.h"

#include <stdio.h>
#include <string.h>
#include <unistd.h>

void bb_custom_builder_init(struct bb_custom_builder* bdr, struct bb_view* view,
                            char const* build_all_cmd,
                            char const* clean_cmd,
                            char const* incremental_build_cmd)
{
    bb_system_command_init(&(bdr->clear_screen_command), "clear");
    bb_system_command_init(&(bdr->build_all_command), build_all_cmd);
    bb_system_command_init(&(bdr->clean_command), clean_cmd);
    bb_system_command_init(&(bdr->incremental_build_command), incremental_build_cmd);
    bdr->action_counter = 0;
    bdr->view = view;
}

void bb_custom_builder_uninit(struct bb_custom_builder* bdr)
{
    bb_system_command_uninit(&(bdr->incremental_build_command));
}

void bb_custom_builder_on_filesystem_change(
    struct bb_custom_builder* bdr, struct bb_filesystem_change const* change)
{
    (void)change;
    char const* line; size_t len;
    struct timeval before, after;
    char buffer[256];

    // Clear screen
    bb_system_command_start(&(bdr->clear_screen_command));
    while (bb_system_command_get_output_line(&(bdr->clear_screen_command), &line, &len)) ;

    // Incremental build
    ++bdr->action_counter;
    bb_current_time(&before);
    bb_announce_event(&before, bdr->action_counter, "performing incremental build");
    bb_system_command_start(&(bdr->incremental_build_command));
    while (bb_system_command_get_output_line(&(bdr->incremental_build_command), &line, &len))
    {
        bb_view_on_build_output(bdr->view, line);
    }
  
    // Finish up
    bb_current_time(&after);
    double const elapsed_seconds = 
        (after.tv_sec - before.tv_sec) + (after.tv_usec - before.tv_usec) / 1000000.0;
    sprintf(buffer, "incremental build complete! (%.3f seconds)", elapsed_seconds);
    bb_announce_event(&after, bdr->action_counter, buffer);
    fflush(stdout);
}

